// 实现这个项目的构建任务
const { src, dest, parallel, series, watch } = require("gulp")

const browserSync = require("browser-sync")
const bs = browserSync.create()
const del = require("del")

const plugins = require("gulp-load-plugins")() // gulp-load-plugins插件方法

// 定义清除任务
const clean = () => {
  return del(["dist"])
}

// 定义css任务
const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass({ outputStyle: "expanded" }))
    .pipe(dest("dist"))
    .pipe(bs.reload({stream: true}))
}

// 定义js任务
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["babel-preset-env"] }))
    .pipe(dest("dist"))
    .pipe(bs.reload({stream: true}))
}

// 定义HTML任务
const html = () => {
  return src("src/**/*.html", { base: "src" })
    .pipe(plugins.swig())
    .pipe(dest("dist"))
    .pipe(bs.reload({stream: true}))
}

// 定义image图片任务
const image = () => {
  return src("src/assets/images/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"))
}

// 定义字体任务
const font = () => {
  return src("src/assets/fonts/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"))
}

// 额外文件
const extra = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"))
}

// useref 可以将html 中引用的css js 问价压缩合并，减少请求
const useref = () => {
  return src('dist/*.html', {base: 'dist'})
    .pipe(plugins.useref({searchPath: ['dist', '.']}))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(plugins.if(/\.html$/, plugins.htmlmin({
      collapseWhitespace: true,
      removeComments: true,
      minifyCss: true, // 压缩页面css
      minifyJs: true // 压缩页面js
    })))
    .pipe(dest('release')) // 使用release 从 dist文件读取编写到release
}

// 定义服务器
// 通过browserSync 设置服务器，
// watch api 监听文件的变化
const serve = () => {
  watch("src/assets/styles/*.scss", style)
  watch("src/assets/styles/*.scss", script)
  watch("src/**/*.html", html)
  // watch("src/assets/images/**", image)
  // watch('src/assets/fonts/**', font)
  // watch("public/**", extra)
  watch([
    "src/assets/images/**", 'src/assets/fonts/**', "public/**"
  ], bs.reload)

  bs.init({
    notify: false,
    port: 2020,
    // open: false,
    // files: "dist/**", // 同理也可以通过browserSync.reload 方法加载
    server: {
      baseDir: ["dist", "src", "public"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  })
}

const compile = parallel(style, script, html)

// 上线之前
const build = series(clean, parallel(compile, image, font, extra))

const dev = series(parallel(compile), serve)

module.exports = {
  clean,
  compile,
  build,
  dev,
  useref
}